//index.js
//获取应用实例
var app = getApp()
var Keys = require('../../assets/data/keys')
var CommonUtils = app.CommonUtils

Page({
  data: {
    orderType: false, //订单类型， false： 立即支付下单 或  true： 购物车下单，默认立即支付下单，
    addressData: '',
    goodsList: [],
    allGoodsPrice: 0,
    address_id: '',
    yunPrice: 0,
    allGoodsAndYunPrice: 0,
    goodsJsonStr: "",
    hasNoCoupons: true,
    coupons: [],
    youhuijine: 0, //优惠券金额
    curCoupon: null, // 当前选择使用的优惠券
    btnBuyNowPay: false,
    btnZiJiAnZhuang: true
  },

  onLoad: function (e) {
    var _this = this;
    if (e.orderType == "buyShopping") {
      _this.setData({
        orderType: true,
      })
    }
    _this.setData({
      btnBuyNowPay: false,
    })

    wx.getStorage({
      key: 'buyNowInfo',
      success: function (res) {
        _this.setData({
          goodsList: res.data.shopList,
        })
        _this.initOtherData();
      },
    })
    _this.initAddress();
  },

  onShow: function () {
    console.log("出现");
    var _this = this;
    try {
      var value = wx.getStorageSync('AddressInfo')
      if (value) {
        console.log("mmmmmmmm")
        console.log(value);
        _this.setData({
          addressData: value
        })
        try {
          wx.removeStorageSync('AddressInfo')
        } catch (e) {
          // Do something when catch error
        }
        console.log(_this.data.addressData);
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  

  /**
   * 初始化其他数据   总价......等
   */
  initOtherData: function () {
    let totalPrice = 0, shopNum = this.data.goodsList.length;
    for (let i = 0; i < shopNum; i++) {
      totalPrice = totalPrice + parseFloat(this.data.goodsList[i].num) * parseFloat(this.data.goodsList[i].price)
    }
    this.setData({
      allGoodsPrice: totalPrice.toFixed(2),
    })
  },

  /**
   * 初始化地址
   */
  initAddress: function () {
    var _this = this;
    wx.showLoading();
    wx.request({
      url: "http://172.18.1.155:8017/api/Address.ashx?",
      data: {
        DataType: "DefaultAddress",
				Token: getApp().data.Token
      },
      success: (res) => {
        console.log("aaaa");
        console.log(res);
        console.log("aaaaa");
        if (res.data.isok == "fasle") {

        } else {
          _this.setData({
            addressData: res.data.data,
          })
        }
      },
      complete: (res) => {
        wx.hideLoading()
      }
    })
  },

  /**
   * 初始化商品列表
   */
  initGoodsList: function () {
    var _this = this;
    var aa = wx.getStorageSync("buyNowInfo")
    if (_this.data.orderType == "buyNow") {
      console.log(aa)
    } else {
      console.log(aa)
    }
  },
  //
  /**
   * 选择地址
   */
  selectAddress: function () {
    wx.navigateTo({
      url: "/pages/W_AddressList/index?IsSelectAddress=" + true
    })
  },

  /**
   * 创建订单
   */
  createOrder: function (e) {
    var remark = ""; // 备注信息
    if (e) {
      remark = e.detail.value.remark; // 备注信息
    }
    if (this.data.addressData == null) {
      CommonUtils.showToastWithImg("请选择地址", 2)
    } else {
      if (!this.data.orderType) {
        this.createOrderBuyNow(remark)
      } else {
        this.createOrderBuyCar(remark)
      }
    }
  },

  /**
   * 立即购买创建订单
   */
  createOrderBuyNow: function (remark) {
    var _this = this;
    if (_this.data.btnBuyNowPay) {
      CommonUtils.showToastWithImg("订单已生成", 2)
      return
    }
    wx.request({
      url: Keys.data.url_Order_Product_Add,
      data: {
        DataType: "Order_Product_Add",
        uid: app.login_id,
        haid: _this.data.addressData.HA_ID,
        pid: _this.data.goodsList[0].id,
        firstcount: parseInt(_this.data.goodsList[0].num),
        note: remark
      },
      success: function (res) {
        console.log(res)
        if (res.data.isok == "true") {
          _this.setData({
            btnBuyNowPay: true,
          })
          _this.toBuy(res.data.data.HO_ID)
        } else {
          CommonUtils.showToastWithImg(res.data.info, 2)
        }
      }
    })
  },
  /**
   * 购物车购买创建订单
   */
  createOrderBuyCar: function (remark) {
    var _this = this;
    if (_this.data.btnBuyNowPay) {
      CommonUtils.showToastWithImg("订单已生成", 2)
      return
    }
    var c_id = "", first_count = "";
    for (var i = 0; i < _this.data.goodsList.length; i++) {
      c_id += _this.data.goodsList[i].car_id + ","
      first_count += _this.data.goodsList[i].num + ","
    }
    wx.request({
      url: Keys.data.url_Order_Add,
      data: {
        DataType: "Order_Add",
        uid: app.login_id,
        haid: _this.data.addressData.HA_ID,
        cid: c_id,
        firstcount: first_count,
        note: remark
      },
      success: function (res) {
        console.log(res)
        if (res.data.isok == "true") {
          _this.setData({
            btnBuyNowPay: true,
          })
          _this.toBuy(res.data.data.HO_ID)
        } else {
          CommonUtils.showToastWithImg(res.data.info, 2)
        }
      }
    })
  },

  /**
   * 调用微信支付
   */
  toBuy: function (ho_id) {
    console.log(ho_id)
    wx.request({
      url: Keys.data.url_pay,
      data:{
        DataType:"Xcx_WxPay",
        uid:app.login_id,
        openid:app.open_id,
        oid: ho_id
      },
      success:function(res){
        console.log(res.data)
        wx.requestPayment({
          timeStamp: res.data.data.timeStamp,
          nonceStr: res.data.data.nonceStr,
          "package": res.data.data.package,
          signType: 'MD5',
          paySign: res.data.data.paySign,
          fail: function (aaa) {
            wx.showToast({ title: '支付失败:' + aaa })
          },
          success: function () {
            wx.showToast({ title: '支付成功' })
            wx.redirectTo({
              url: '../order-list/index'
            });
          }
        })
      }
    })
  },

  ClickedZiji:function(){
    var _this = this;
    _this.setData({
      btnZiJiAnZhuang: true,
    })
  },

  ClickedFuwu:function(){
    var _this = this;
    _this.setData({
      btnZiJiAnZhuang: false,
    })
  }




  // createOrder: function (e) {
  //   wx.showLoading();
  //   var that = this;
  //   var remark = ""; // 备注信息
  //   if (e) {
  //     remark = e.detail.value.remark; // 备注信息
  //   }

  //   var postData = {
  //     goodsJsonStr: that.data.goodsJsonStr,
  //     remark: remark
  //   };
  //   if (that.data.isNeedLogistics > 0) {
  //     if (!that.data.curAddressData) {
  //       wx.hideLoading();
  //       wx.showModal({
  //         title: '错误',
  //         content: '请先设置您的收货地址！',
  //         showCancel: false
  //       })
  //       return;
  //     }
  //     postData.provinceId = that.data.curAddressData.provinceId;
  //     postData.cityId = that.data.curAddressData.cityId;
  //     if (that.data.curAddressData.districtId) {
  //       postData.districtId = that.data.curAddressData.districtId;
  //     }
  //     postData.address = that.data.curAddressData.address;
  //     postData.linkMan = that.data.curAddressData.linkMan;
  //     postData.mobile = that.data.curAddressData.mobile;
  //     postData.code = that.data.curAddressData.code;
  //   }
  //   if (that.data.curCoupon) {
  //     postData.couponId = that.data.curCoupon.id;
  //   }
  //   if (!e) {
  //     postData.calculate = "true";
  //   }


  //   wx.request({
  //     url: 'https://api.it120.cc/' + app.globalData.subDomain + '/order/create',
  //     method: 'POST',
  //     header: {
  //       'content-type': 'application/x-www-form-urlencoded'
  //     },
  //     data: postData, // 设置请求的 参数
  //     success: (res) => {
  //       wx.hideLoading();
  //       if (res.data.code != 0) {
  //         wx.showModal({
  //           title: '错误',
  //           content: res.data.msg,
  //           showCancel: false
  //         })
  //         return;
  //       }

  //       if (e && "buyNow" != that.data.orderType) {
  //         // 清空购物车数据
  //         wx.removeStorageSync('shopCarInfo');
  //       }
  //       if (!e) {
  //         that.setData({
  //           isNeedLogistics: res.data.data.isNeedLogistics,
  //           allGoodsPrice: res.data.data.amountTotle,
  //           allGoodsAndYunPrice: res.data.data.amountLogistics + res.data.data.amountTotle,
  //           yunPrice: res.data.data.amountLogistics
  //         });
  //         // that.getMyCoupons();
  //         return;
  //       }
  //       // 配置模板消息推送
  //       var postJsonString = {};
  //       postJsonString.keyword1 = { value: res.data.data.dateAdd, color: '#173177' }
  //       postJsonString.keyword2 = { value: res.data.data.amountReal + '元', color: '#173177' }
  //       postJsonString.keyword3 = { value: res.data.data.orderNumber, color: '#173177' }
  //       postJsonString.keyword4 = { value: '订单已关闭', color: '#173177' }
  //       postJsonString.keyword5 = { value: '您可以重新下单，请在30分钟内完成支付', color: '#173177' }
  //       app.sendTempleMsg(res.data.data.id, -1,
  //         'uJQMNVoVnpjRm18Yc6HSchn_aIFfpBn1CZRntI685zY', e.detail.formId,
  //         'pages/index/index', JSON.stringify(postJsonString));
  //       postJsonString = {};
  //       postJsonString.keyword1 = { value: '您的订单已发货，请注意查收', color: '#173177' }
  //       postJsonString.keyword2 = { value: res.data.data.orderNumber, color: '#173177' }
  //       postJsonString.keyword3 = { value: res.data.data.dateAdd, color: '#173177' }
  //       app.sendTempleMsg(res.data.data.id, 2,
  //         'GeZutJFGEWzavh69savy_KgtfGj4lHqlP7Zi1w8AOwo', e.detail.formId,
  //         'pages/order-details/index?id=' + res.data.data.id, JSON.stringify(postJsonString));
  //       // 下单成功，跳转到订单管理界面
  //       wx.redirectTo({
  //         url: "/pages/order-list/index"
  //       });
  //     }
  //   })
  // },


  // initShippingAddress: function () {
  //   var that = this;
  //   wx.request({
  //     url: 'https://api.it120.cc/' + app.globalData.subDomain + '/user/shipping-address/default',
  //     data: {
  //       token: "123"
  //     },
  //     success: (res) => {
  //       if (res.data.code == 0) {
  //         that.setData({
  //           curAddressData: res.data.data
  //         });
  //       } else {
  //         that.setData({
  //           curAddressData: null
  //         });
  //       }
  //       that.processYunfei();
  //     }
  //   })
  // },
  // processYunfei: function () {
  //   var that = this;
  //   var goodsList = this.data.goodsList;
  //   var goodsJsonStr = "[";
  //   var isNeedLogistics = 0;
  //   var allGoodsPrice = 0;

  //   for (let i = 0; i < goodsList.length; i++) {
  //     let carShopBean = goodsList[i];
  //     if (carShopBean.logistics) {
  //       isNeedLogistics = 1;
  //     }
  //     allGoodsPrice += carShopBean.price * carShopBean.number;

  //     var goodsJsonStrTmp = '';
  //     if (i > 0) {
  //       goodsJsonStrTmp = ",";
  //     }


  //     let inviter_id = 0;
  //     let inviter_id_storge = wx.getStorageSync('inviter_id_' + carShopBean.goodsId);
  //     if (inviter_id_storge) {
  //       inviter_id = inviter_id_storge;
  //     }


  //     goodsJsonStrTmp += '{"goodsId":' + carShopBean.goodsId + ',"number":' + carShopBean.number + ',"propertyChildIds":"' + carShopBean.propertyChildIds + '","logisticsType":0, "inviter_id":' + inviter_id + '}';
  //     goodsJsonStr += goodsJsonStrTmp;


  //   }
  //   goodsJsonStr += "]";
  //   //console.log(goodsJsonStr);
  //   that.setData({
  //     isNeedLogistics: isNeedLogistics,
  //     goodsJsonStr: goodsJsonStr
  //   });
  //   that.createOrder();
  // },

  // addAddress: function () {
  //   wx.navigateTo({
  //     url: "/pages/address-add/index"
  //   })
  // },


  // getMyCoupons: function () {
  //   var that = this;
  //   wx.request({
  //     url: 'https://api.it120.cc/' + app.globalData.subDomain + '/discounts/my',
  //     data: {
  //       token: app.globalData.token,
  //       status: 0
  //     },
  //     success: function (res) {
  //       if (res.data.code == 0) {
  //         var coupons = res.data.data.filter(entity => {
  //           return entity.moneyHreshold <= that.data.allGoodsAndYunPrice;
  //         });
  //         if (coupons.length > 0) {
  //           that.setData({
  //             hasNoCoupons: false,
  //             coupons: coupons
  //           });
  //         }
  //       }
  //     }
  //   })
  // },

  // bindChangeCoupon: function (e) {
  //   const selIndex = e.detail.value[0] - 1;
  //   if (selIndex == -1) {
  //     this.setData({
  //       youhuijine: 0,
  //       curCoupon: null
  //     });
  //     return;
  //   }
  //   this.setData({
  //     youhuijine: this.data.coupons[selIndex].money,
  //     curCoupon: this.data.coupons[selIndex]
  //   });
  // }
})
